﻿using System;
using System.Windows.Forms;
using SharePointUtilitiesForDevelopers.Client.Forms;

namespace SharePointUtilitiesForDevelopers.Client
{
    /// <summary>
    /// The main program.
    /// </summary>
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            try
            {
                Application.Run(ServiceLocator.Resolve<MainForm>());
            }
            catch (Exception ex)
            {
                DisplayExceptionMessage(ex);
            }
            finally
            {
                Application.Exit();
            }
        }

        /// <summary>
        /// Handles the UnhandledException event of the CurrentDomain control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.UnhandledExceptionEventArgs"/> instance containing the event data.</param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            DisplayExceptionMessage(e.ExceptionObject as Exception);

            if (!e.IsTerminating)
            {
                Application.Exit();
            }
        }
        
        /// <summary>
        /// Displays the exception message.
        /// </summary>
        static void DisplayExceptionMessage(Exception ex)
        {
            var errorReportForm = new ErrorReportForm(ex, Properties.Resources.ApplicationName, ex.Message);
            errorReportForm.ShowDialog();
        }
    }
}